#include <stdio.h>

#include <Windows.h>
#include <lm.h>

int u8_to_gb2312(char* in, char* out, int* out_len)
{
	char* mid;
	int len;

	//convert an MBCS string to widechar, in to mid
	len = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)in, -1, NULL, 0);
	len = len * sizeof(wchar_t);
	mid = malloc(len);
	MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)in, -1, (LPWSTR)mid, len);

	//mid to out
	len = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)mid, -1, NULL, 0, NULL, NULL);
	WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)mid, -1, (LPSTR)out, len, NULL, NULL);

	free(mid);
	*out_len = len;
	out[len] = 0;
	return 0;
}

static char outbuf_debug[1024*32];
void printf_utf8(char* buf)
{
	int outlen;
	u8_to_gb2312(buf, outbuf_debug, &outlen);
	printf("%s", outbuf_debug);
}

char* u16_to_u8(char* in, int* out_len)
{
	int len;
	//Maps a UTF-16 (wide character) string to a new character string. 
	len = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)in, -1, NULL, 0, NULL, NULL);

	char* out = malloc(len);
	WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)in, -1, (LPSTR)out, len, NULL, NULL);
	if (out_len)
		*out_len = len;
	return out;
}

//utf_content = to_utf(buf, &realsize);
//gb2312 to utf8, should free memory by caller
char* to_utf(char* in, int* out_len)
{
	char* mid;
	char* out;
	int len;

	//in to mid
	//Maps a character string to a UTF-16 (wide character) string
	len = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)in, -1, NULL, 0);
	len = len * sizeof(wchar_t);
	mid = malloc(len);
	MultiByteToWideChar(CP_ACP, 0, (LPCSTR)in, -1, (LPWSTR)mid, len);

	//mid to out
	//Maps a UTF-16 (wide character) string to a new character string. 
	len = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)mid, -1, NULL, 0, NULL, NULL);
	out = malloc(len);
	WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)mid, -1, (LPSTR)out, len, NULL, NULL);

	free(mid);
	*out_len = len;
	return out;
}

//////////////////////

void get_filename(char* path, char* filename)
{
	char* temp;

	temp = strstr(path, ".pdf");
	if (!temp) {
		return;
	}
	*temp = 0;
	strcpy(filename, path);
	*temp = '.';
}
